package com.demo.mybatis_plus.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.mybatis_plus.dto.ReservationParam;
import com.demo.mybatis_plus.mapper.PetInfoMapper;
import com.demo.mybatis_plus.mapper.ReservationMapper;
import com.demo.mybatis_plus.pojo.PetInfo;
import com.demo.mybatis_plus.pojo.Reservation;
import com.demo.mybatis_plus.pojo.Userinfo;
import com.demo.mybatis_plus.util.DatetimeUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ReservationService extends ServiceImpl<ReservationMapper, Reservation> {
    @Resource
    private UserinfoService userinfoService;
    @Resource
    private PetInfoMapper petInfoMapper;
    @Resource
    private ReservationMapper reservationMapper;

    public List<Reservation> getAll(ReservationParam param) {
        return reservationMapper.queryAll(param);
    }

    /**
     * 创建一个预约
     *
     * @param param
     * @return
     */
    @Transactional // 事务
    public Reservation create(ReservationParam param) {
        // 1.创建用户信息
        Userinfo userinfo = new Userinfo();
        userinfo.setName(param.getName());
        userinfo.setPhone(param.getPhone());
        userinfoService.save(userinfo);

        // 2.创建宠物信息
        PetInfo pet = new PetInfo();
        pet.setName(param.getPetName());
        pet.setCategory(param.getPetCategory());
        pet.setUid(userinfo.getId()); // 设置宠物和用户的关联
        petInfoMapper.insert(pet);
        // 3.创建预约

        Reservation r = new Reservation();
        r.setUid(userinfo.getId()); // 设置用户关联
        r.setPetId(pet.getId()); // 设置宠物关联
        r.setReason(param.getReason());
        r.setReserveTime(param.getReserveTime());
        reservationMapper.insert(r);
        return r;
    }

    public Reservation verify(Integer id, String phone) {

        // 1.根据2个参数选择1个进行查询 然后再进行比值判断
        // 2.让mybatis构建查询的sql进行操作
        // 选择第一种 使用mybatis-plus的querywrapper进行查询
        QueryWrapper q = new QueryWrapper();
        if (id != null) {
            q.eq("id", id);
        } else {
            q.like("reserve_time", "%" + DatetimeUtils.format("yyyy-MM-dd") + "%");
        }
        if (phone != null) {
//            q.eq("phone")
            // 由于手机号码不是预约表的数据 所以需要先查用户
            final Userinfo userinfo = userinfoService.getByPhone(phone);
            // 可能手机号码不存在
            if (null == userinfo) {
                throw new RuntimeException("预约的手机号码不存在");
            }
            q.eq("uid", userinfo.getId()); // 设置uid
        }

        final Reservation reservation = reservationMapper.selectOne(q);
        return reservation;
    }
}
